package com.jeespring.atomikos.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jta.atomikos.AtomikosDataSourceBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.jeespring.atomikos.orderdao", sqlSessionFactoryRef = "orderSqlSessionFactory")
public class OrderDatabaseConfig {
    /**
     * 设置JTA(Atomikos)数据源
     *
     * @return {@link AtomikosDataSourceBean}
     */
    @Primary
    @Bean(name = "orderAtomikosDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.druid.one")
    public DataSource getDataSource() {
        return new AtomikosDataSourceBean();
    }

    /**
     * 设置Mybatis的会话工厂类
     *
     * @param dataSource JTA(Atomikos)数据源
     * @return {@link SqlSessionFactoryBean#getObject()}
     * @throws Exception
     */
    @Primary
    @Bean(name = "orderSqlSessionFactory")
    public SqlSessionFactory getSqlSessionFactory(@Qualifier("orderAtomikosDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        bean.setMapperLocations(resolver.getResources("classpath:mapper/order/*.xml"));
        return bean.getObject();
    }
}
